package com.by.yz.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.NetworkImageView;
import com.by.yz.App;
import com.by.yz.R;
import com.by.yz.activity.base.BaseActivity;
import com.by.yz.entity.Account;
import com.by.yz.entity.UserTest;
import com.by.yz.loginUtil.AccountRESTFul;
import com.by.yz.loginUtil.UserRESTFul;
import com.by.yz.mypersonal.PersonalUpdateInfoActivity;
import com.by.yz.util.ToJSonObject;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/**
 * Created by 123 on 2016/10/7.
 */

public class PersonalEditActivity extends BaseActivity implements View.OnClickListener {
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESIZE_REQUEST_CODE = 2;

    private static final String IMAGE_FILE_NAME = "header.jpg";
    private NetworkImageView networkImageView;//个人头像
    private RelativeLayout update;
    private RelativeLayout picture;
    private RelativeLayout sex;
    private View vis;
    private Button pop,cramera,xiangce;
    private TextView set_sex,login,nickName;
    Account account;
    UserTest userTest;
    Uri photoUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personal_edit_activity);
        setToolbarTitle("个人资料");
    }

    @Override
    protected void onStart(){
        super.onStart();
        initDatas();
        initView();
    }

    @Override
    protected void onRestart(){
        super.onRestart();
    }

    private void initDatas() {
        AccountRESTFul accountRESTFul=new AccountRESTFul();
        accountRESTFul.get(new AccountRESTFul.IhttpCb() {
            @Override
            public void ok(JSONObject response) {
                Log.e("PEA-account",response.toString());
                JSONObject jsonObject=response;
                account= ToJSonObject.jsonToBean(jsonObject.toString(),Account.class);
                login.setText(account.getLogin());
                UserRESTFul userRESTFul=new UserRESTFul();
                userRESTFul.getUser(account.getLogin(), new UserRESTFul.UserPOSTCallBack() {
                    @Override
                    public void ok(JSONObject response) throws JSONException {
                        Log.e("PEA-user-success",response.toString());
                        JSONObject jsonObject=response;
                        userTest=ToJSonObject.jsonToBean(jsonObject.toString(),UserTest.class);
                        nickName.setText(userTest.getnickName());
                        if(userTest.getsex()){
                            set_sex.setText("男");
                        }else{
                            set_sex.setText("女");
                        }
                    }

                    @Override
                    public void error(String response) {
                        Log.e("PEActivity-user-failed","获取用户表失败"+response);
                    }
                });
            }

            @Override
            public void error(String error) {
                Log.e("PEActivity-account","授权失败"+error);
            }
        });
    }

    private void initView() {
//        Intent intent=this.getIntent();
//        final UserTest user=(UserTest)intent.getSerializableExtra("user");
        //个人头像
        networkImageView = (NetworkImageView) findViewById(R.id.headerPicture);
        networkImageView.setDefaultImageResId(R.mipmap.personal_contacts_list_02);
        networkImageView.setErrorImageResId(R.mipmap.personal_contacts_list_01);
        networkImageView.setImageUrl("http://img.my.csdn.net/uploads/201404/13/1397393290_5765.jpeg",
                App.imageLoader);

        update = (RelativeLayout) findViewById(R.id.pc_updateinfo);
        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Context context = view.getContext();
                Intent intent=new Intent(context,PersonalUpdateInfoActivity.class);
                Bundle bundle=new Bundle();
                bundle.putSerializable("user1",userTest);
                intent.putExtras(bundle);
                context.startActivity(intent);
            }
        });
        picture = (RelativeLayout) findViewById(R.id.personalpicture);
        picture.setOnClickListener(this);
        // 登录名
        login=(TextView)findViewById(R.id.personal_edit_login);
        // 昵称
        nickName=(TextView)findViewById(R.id.personal_edit_nickName);
        // 性别
        sex = (RelativeLayout) findViewById(R.id.pc_sex);
        sex.setOnClickListener(this);
        // 显示性别
        set_sex = (TextView) findViewById(R.id.sex);
        // 弹出拍照和相册选择
        vis = findViewById(R.id.ll_popup);
        // 取消按钮
        pop = (Button) findViewById(R.id.item_popupwindows_cancel);
        pop.setOnClickListener(this);
        // 打开相册
        xiangce=(Button)findViewById(R.id.item_popupwindows_Photo);
        xiangce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
                galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
                galleryIntent.setType("image/*");//图片
                startActivityForResult(galleryIntent, IMAGE_REQUEST_CODE);
            }
        });
        // 相机
        cramera=(Button)findViewById(R.id.item_popupwindows_camera);
        cramera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isSdcardExisting()) {
                    Intent cameraIntent = new Intent("android.media.action.IMAGE_CAPTURE");//拍照
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, getImageUri());
                    cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
                } else {
                    Toast.makeText(view.getContext(), "请插入sd卡", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){

            case R.id.personalpicture:
                vis.setVisibility(View.VISIBLE);
                vis.setOnClickListener(null);
                break;

            case R.id.pc_sex:
                final AlertDialog.Builder builder = new AlertDialog.Builder(PersonalEditActivity.this); //定义选择性别对话框
                final String[] strarr = {"男", "女"};
                builder.setItems(strarr, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        boolean sex = true;
                        set_sex.setText("男");
                        if (arg1 == 1) {//女
                            sex = false;
                            set_sex.setText("女");
                        }
                        if(sex!=userTest.getsex()){
                            userTest.setsex(sex);
                            JSONObject jsonObject=ToJSonObject.beanToJSONObejct(userTest);
                            UserRESTFul userRESTFul=new UserRESTFul();
                            userRESTFul.putUser(jsonObject, new UserRESTFul.UserPOSTCallBack() {
                                @Override
                                public void ok(JSONObject response) throws JSONException {
                                    Toast.makeText(getApplicationContext(), "修改性别成功", Toast.LENGTH_SHORT).show();
                                }
                                @Override
                                public void error(String response) {
                                    Toast.makeText(getApplicationContext(), "修改性别失败，请检查网络", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                });
                builder.show();
                break;

            case R.id.item_popupwindows_cancel:
                vis.setVisibility(View.INVISIBLE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        } else {
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    resizeImage(data.getData());
                    break;
                case CAMERA_REQUEST_CODE:
                    if (isSdcardExisting()) {
                        resizeImage(getImageUri());
                    } else {
                        Toast.makeText(PersonalEditActivity.this, "未找到存储卡，无法存储照片！",
                                Toast.LENGTH_LONG).show();
                    }
                    break;

                case RESIZE_REQUEST_CODE:
                    if (data != null) {
                        showResizeImage(data);
                    }
                    break;
            }
            vis.setVisibility(View.INVISIBLE);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    private boolean isSdcardExisting() {//判断SD卡是否存在
        final String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    public void resizeImage(Uri uri) {//重塑图片大小
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");//可以裁剪
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RESIZE_REQUEST_CODE);
    }

    private void showResizeImage(Intent data) {//显示图片
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(photo);
            networkImageView.setImageDrawable(drawable);
        }
    }

    private Uri getImageUri() {//获取路径
        return Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                IMAGE_FILE_NAME));
    }

}
